# -*- encoding: utf-8 -*-
"""
@File:        DatasourceService.py
@Author:      Little duo
@Time:        2024/4/12 9:34 
@Contact:     1049041957@qq.com
"""
from typing import Optional
from sqlalchemy.orm import Session
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.user_vo import CurrentUserModel
from . import DatasourcePageQueryModel, DatasourceModel, DeleteDatasourceModel, DatasourceDao


class DatasourceService:

    @classmethod
    def getDatasourceById(cls, query_db: Session, current_user: Optional[CurrentUserModel] = None):
        return DatasourceDao.getDatasourceById(query_db, current_user.user.user_id)

    @classmethod
    def getDatasourceList(cls, query_db: Session, obj: DatasourcePageQueryModel, is_page: bool = True):
        return DatasourceDao.getDatasourceList(query_db, obj, is_page)

    @classmethod
    def addDatasource(cls, query_db: Session, model: DatasourceModel):
        try:
            DatasourceDao.addDatasource(query_db, model)
            query_db.commit()
            result = dict(is_success=True, message='新增数据源成功')
        except Exception as e:
            query_db.rollback()
            result = dict(is_success=False, message=f'新增数据源失败：{e}')
            raise e
        return CrudResponseModel(**result)

    @classmethod
    def updateDatasource(cls, query_db: Session, model: DatasourceModel):
        row = cls.getDatasourceById(query_db, model.datasource_id)
        if not row:
            result = dict(is_success=False, message='数据源不存在')
        else:
            try:
                data = model.model_dump(exclude_unset=True)
                DatasourceDao.updateDatasource(query_db, data)
                query_db.commit()
                result = dict(is_success=True, message='更新数据源成功')
            except Exception as e:
                query_db.rollback()
                result = dict(is_success=False, message=f'更新数据源失败: {e}')
                raise e
        return CrudResponseModel(**result)

    @classmethod
    def deleteDatasource(cls, query_db: Session, model: DeleteDatasourceModel):
        try:
            for datasource_id in model.datasource_id_list:
                DatasourceDao.deleteDatasource(query_db, datasource_id)
            query_db.commit()
            result = dict(is_success=True, message='删除成功')
        except Exception as e:
            query_db.rollback()
            raise e
        return CrudResponseModel(**result)
